<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}


	public function actionLogin() {
	    $model = new UserLoginForm();

	    if (isset($_POST['UserLoginForm'])) {
	        $model->attributes = $_POST['UserLoginForm'];

	        if ($model->validate()) {
                $identity = new UserIdentity($model->login, $model->password);
                if ($identity->authenticate()) {
                    Yii::app()->user->login($identity);
                    if (!Yii::app()->request->getIsAjaxRequest()) {
                        Yii::app()->request->redirect(Yii::app()->user->returnUrl);
                    } else {
                        // TODO: some usefull staff
                    }
                } else {
                    $model->addError("password", "Couldn't autentificate user with such login/password pair");
                }
	        }
	    }

        $this->render("login", array("model" => $model));
	}

	public function actionLogout() {
	    Yii::app()->user->logout();
	    Yii::app()->request->redirect("/");
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}
}